	package com.yourwork.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.yourwork.dao.ClienteleDao;
import com.yourwork.model.Clientele;
import com.yourwork.service.ClienteleService;

@Controller
@RequestMapping(value="/clientele")
/**
 * 用户管理
 * **/
public class ClienteleController {
	@Autowired
	@Qualifier(value="customerService")
	private ClienteleService customerService;
	@Autowired
	@Qualifier(value="clienteleDao")
	private ClienteleDao clienteleDao;
	/**
	 * 分页查询
	 *Attribute名 customerPage
	 *@param page 页数
	 *@param size 每页显示的条数
	 * **/
	@RequestMapping(value="/select",method={RequestMethod.GET})
	private String queryCustomer(Model m,@RequestParam(name="page",required=false,defaultValue="0")int page,
			@RequestParam(name="size",required=false,defaultValue="10")int size,HttpSession session){
			Page<Clientele> customerPage = customerService.queryCustomer(page,size);
			List<Clientele> list = new ArrayList<Clientele>();
			for(Clientele c: customerPage){
				list.add(c);
			}
			int count1 = customerService.countCustomer();
			addAttribute(m, "list", list, true);
			//得到末页
			int maxPage = customerService.queryMaxPage(page,size);
			m.addAttribute("maxPage", maxPage);
			m.addAttribute("page", page);//attribute中存入page
			m.addAttribute("size", size);//attribute中存入size
			m.addAttribute("count", count1);//用户的总数
			m.addAttribute("managerNumber", session.getAttribute("managerNumber"));//获取session中的值
			m.addAttribute("remind", session.getAttribute("remind"));//获取session中的提示信息
			session.setAttribute("remind", "");//清空session中的remind的数据
			return "/work/customer";	
	}
	//修改用户记录
	@RequestMapping(value="/modify",method={RequestMethod.POST})
	public String updateCustomer(@ModelAttribute(name="customer") Clientele customer,
			HttpSession session){
		String remind = customerService.updateCustomer(customer);
		//像session中存入remind
		session.setAttribute("remind", remind);
		return "redirect:/clientele/select";
	}
	
	private void addAttribute(Model m,String attributeName,Object attributeValue,boolean replace){
		if(replace==true){//判断是否添加attribute
			m.addAttribute(attributeName, attributeValue);
		}else{
			if(!m.containsAttribute(attributeName)){//判断是否已经存在的attribute
				m.addAttribute(attributeName, attributeValue);
			}
		}
	}
}
